package com.lry.basic.algorithm.loadbanlance;

import java.util.Random;

/**
 * 加权随机
 */
public class WeightRandom {

    public static Server getServer(){
        int totalWeight = 0;
        for(Server server:WeightServer.servers){
            totalWeight +=server.getWeight();
        }

        int pos = new Random().nextInt(totalWeight);

        for(Server server:WeightServer.servers){
            if(pos<server.getWeight()){
                return server;
            }
            pos-=server.getWeight();
        }
        return null;
    }

    public static void main(String[] args) {

        for(int i=0;i<1000;i++){
            Server server = getServer();
            server.setCallNum(server.getCallNum()+1);
        }
        for(Server server:WeightServer.servers){
            System.out.println(server);
        }
    }
}
